import axios from 'axios'
import {
  getToken
} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'https://www.xiandu001.com/api',
  timeout: 5000
})
const noTokenRequest = ['/xiandu/admin/v1/account_login','/xiandu/admin/v1/upload_img'];
// request interceptor
service.interceptors.request.use(
  config => {
    const {
      data
    } = config;

    const token = getToken('token');
    if (data && !noTokenRequest.includes(config.url)) {
      data.token= token;
    }
    // if (token && !noTokenRequest.includes(config.url)) {
    //   config.headers['token'] = token;
    // }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // 操作成功
    if (res.code == 200200) {
      return Promise.resolve(res)
    } 
    else if(res.code == 200500){
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    }
    else { //操作失败
      return Promise.reject(res);
    }
  },
  error => {
    console.log(error);
    return Promise.reject(error)
  }
)

export default service
